import xlrd


class ExcelUtil(object):
    def __init__(self, excel_path, sheet_name="Sheet1"):
        # 打开excel表格
        self.data = xlrd.open_workbook(excel_path)
        # 通过名称获取
        self.table = self.data.sheet_by_name(sheet_name)
        # 获取第一行作为key值
        self.keys = self.table.row_values(0)
        # 获取总行数
        self.rowNum = self.table.nrows
        # 获取总列数
        self.colNum = self.table.ncols

    def excel_data(self):
        if self.rowNum <= 1:
            print("总行数小于1")
        else:
            l = []  # 空列表
            j = 1
            for i in range(self.rowNum - 1):
                s = {}
                # 获取行里的值,以列表的形式存在
                values = self.table.row_values(j)
                for x in range(self.colNum):
                    s[self.keys[x]] = values[x]
                l.append(s)
                j += 1
            return l


if __name__ == '__main__':
    excelPath = '../data/user.xls'
    file = ExcelUtil(excelPath)
    data = file.excel_data()
    print(data)
